<template>
  <div>
    <div class="mgb5 warn-text">(注: 结束个数不能小于开始个数)</div>
    <vxe-table :data="props.configData" border header-align="center" align="center" max-height="500">
      <vxe-column field="s" title="开始个数">
        <template #default="{ row }">
          <el-input v-model="row.s" placeholder="Please input" type="number" :min="1" />
        </template>
      </vxe-column>
      <vxe-column field="s" title="结束个数">
        <template #default="{ row, rowIndex }">
          <el-input v-if="rowIndex !== props.configData.length - 1" v-model="row.e" placeholder="Please input" type="number" :min="1" />
        </template>
      </vxe-column>
      <vxe-column title="操作 ">
        <template #default="{ row, rowIndex }">
          <el-button type="danger" link @click="subConfig(row, rowIndex)">删除</el-button>
          <el-button type="primary" link @click="addConfig(row, rowIndex)">新增 </el-button>
        </template>
      </vxe-column>
    </vxe-table>
    <div class="flex-row-center-right mgt10">
      <el-button @click="emits('cancel')">取消</el-button>
      <el-button type="primary" @click="emits('reset')"> 重置 </el-button>
      <el-button type="primary" @click="handleConfirm"> 确定 </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { Ui, cache } from '@/utils'
  import type { IGraphSetConfig } from '../config'

  interface IProps {
    configData: IGraphSetConfig[]
  }

  interface IEmits {
    (e: 'cancel'): void
    (e: 'handleConfirm'): void
    (e: 'reset'): void
  }

  const props = withDefaults(defineProps<IProps>(), {
    configData: () => []
  })

  const emits = defineEmits<IEmits>()

  /**----------------------------methods----------------------------------------------------------------------- */

  const handleConfirm = () => {
    emits('handleConfirm')
    setCache()
  }

  const addConfig = (row: IGraphSetConfig, index: number) => {
    if (props.configData.length === 12) return Ui.useMessage('warning', '最多配置12个挡位')
    const item: IGraphSetConfig = props.configData[index]
    const newItem: IGraphSetConfig = {
      s: item.e ? item.e + 1 : 1,
      e: item.e ? item.e + 2 : 1
    }

    if (index === props.configData.length - 1) {
      const lastItem = props.configData.at(-1) as IGraphSetConfig
      lastItem.e = lastItem.s + 1
      newItem.s = lastItem.e + 1
      newItem.e = null
    }

    // eslint-disable-next-line vue/no-mutating-props
    props.configData.splice(index + 1, 0, newItem)
  }

  const subConfig = (row: IGraphSetConfig, index: number) => {
    if (props.configData.length === 2) return Ui.useMessage('warning', '最低保留两个挡位')
    // eslint-disable-next-line vue/no-mutating-props
    props.configData.splice(index, 1)
    props.configData.at(-1)!.e = null
  }

  const setCache = () => cache.set('graphCustomerLine', props.configData)
</script>

<style scoped></style>
